package com.xc.stock.domain.basic.repository;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 本地加载缓存
 * 使用于基础/配置型数据 
 *
 * @author rplees
 * @email rplees.i.ly@gmail.com
 * @version 1.0  
 * @created Dec 28, 2021 10:39:24 AM
 */
public abstract class LocalCacheRepository<E, P, ID extends Serializable> extends SimplePoConvertEntityRepository<E, P, ID> {
	protected LocalCacheBean<P, ID> localCache;
	
	public LocalCacheBean<P, ID> localCache() {
		if(localCache == null) {
			localCache = buildLocalCache();
		}
		return localCache;
	}
	
	protected LocalCacheBean<P, ID> buildLocalCache() {
		return new LocalCacheBean<>(repo(), val -> repo().findAll());
	}
	
	public List<E> cacheList() {
		return convert().toEntity(localCache().cacheList());
	}

	public Map<ID, E> cacheMap() {
		return Maps.transformValues(localCache().cacheMap(), val -> convert().toEntity(val));
	}

	public E findCacheById(ID id) {
		return  convert().toEntity(localCache().findCacheById(id));
	}
	
	public List<E> findCacheByIds(List<ID> ids) {
		List<E> list = Lists.newArrayList();
		for (ID id : ids) {
			E e = findCacheById(id);
			if(e != null) {
				list.add(findCacheById(id));
			}
		}
		return list;
	}
}
